
const path = require('path')
Editor.log(__dirname)
/**
 * 分帧处理
 * @param item_arr item数组
 * @param process 处理函数
 * @param finish_cb 结束函数
 * @param time 每帧最大时限
 * @param frame_time 每帧停顿间隔
 * @returns 
 */
function frameProcess(item_arr, process, finish_cb, time = 1, frame_time = 500) {
  let idx = 0;
  function _frameProcess(item_arr, process, finish_cb, time = 1) {
    // console.log('frameProcess')
    let last_time = new Date().getTime()
    while (item_arr.length) {
      if (new Date().getTime() - last_time > 1) {
        setTimeout(() => {
          _frameProcess(item_arr, process, finish_cb);
        }, frame_time)
        return
      }
      let item = item_arr.shift();
      process(item, idx)
      idx++;
    }
    if (finish_cb) finish_cb();
  }
  _frameProcess(item_arr, process, finish_cb, time)
}
let config;
Editor.Panel.extend({
  // css style for panel
  style: `
    ul,li{
      list-style-type：none;
    }
    h2 { color: #f90; }
    
    #content{
      width: 100vw;
      height:90vh;
      
      display:flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      overflow-y:scroll;
    }
    .item{
      width:90vw;
      // flex:1;
      margin-top:5px;
    }
    #title{
      color:red;
      text-align: center;
    }
    #log_wrap{
      height:40%;
      display:flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: flex-start;
      background-color:#1E1E1E;
      overflow-y:scroll;
      // overflow-x:hidden;
      word-wrap: break-word;
    }
    .log_item{
      font-size:1.2rem;
      // padding:2px;
      width:100%;
    }
    .single_log{
      background-color:#000000;
      color:#00C327;
    }
    .double_log{
      background-color:#000000;
      color:#00C327;
    }
    .button_list{
      display:flex;
      flex-direction: row;
      justify-content: flex-end;
      align-items: center;
      flex:1;
    }
    .log_tool_bar{
      display:flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
    }
    .log_tool_bar > last-child{
      flex:1;
    }
  `,

  // html template for panel
  template: `
    <div id="content">
      <h1 id="title">{{title}}</h1>
      <h3 style="width:90vw;">使用说明：默认为pngquant本地压缩,tinypng需要联网使用，并且需要注册账号并填写tinify_key<h3>

      <ui-prop class="item" name="压缩方式"  id="compressType" :value="compress_type" type="enum"
        @confirm="setConfigItem('compress_type',$event.target.value)">
        <option value="0">pngquant</option>
        <option value="1">tinypng</option>
      </ui-prop>
        
        
      <div class="item" v-if="compress_type == 0">
        <ui-prop type="number" name="最小压缩质量" min="0" max="100" 
        @confirm="setConfigItem('min_quality',$event.target.value)"
        :value="min_quality"></ui-prop>

        <ui-prop type="number" name="最大压缩质量" min="0" max="100" 
        @confirm="setConfigItem('max_quality',$event.target.value)"
        :value="max_quality"></ui-prop>
      </div>
      
      <ui-prop name="tinify_key" type="string" class="item" v-else id="tinify_key"
       :value="tinify_key"
       @confirm="setConfigItem('tinify_key',$event.target.value)"
       @confirm="tinify_key = $event.target.value"></ui-prop>
      
      <ui-prop name="忽略已压缩的图片" type="boolean"
        :value="ignore_compressed_png"
        @confirm="setConfigItem('ignore_compressed_png',$event.target.value)"
        @confirm="ignore_compressed_png = $event.target.value"></ui-prop>

      <!-- 
      <ui-prop type="number" name="日志缓冲区大小" min="0" max="65535"  :value="max_log_count"
        @confirm="setConfigItem('max_log_count',$event.target.value)"
        ></ui-prop>
        <ui-prop name="保持日志最新" 
        type="boolean" 
        :value="is_to_bottom_log"
        @confirm="setConfigItem('is_to_bottom_log',$event.target.value)"
        ></ui-prop>
      
      <div class="item log_tool_bar">
        <ui-button  @click="clearAllLog" class="red">清空日志</ui-button>
        <ui-input  @confirm="" value=""></ui-input>
        <ui-checkbox  @confirm="" value="">正则</ui-checkbox>
      </div> 

      <div id="log_wrap" class="item">
      </div>
      -->
      <ui-progress id="compress_progress" class="item" :value="compress_progress" class="large">Large</ui-progress>
      <ui-button id="compress_btn" @click="compress" class="green item">开始压缩</ui-button>
      <p class="item" @click="compress" class="green item"><span>压缩结果：</span>{{compress_judge}}</p>

        <br/>
        <br/>
      构建选项：
      <ui-prop name="构建后检测再压缩" type="boolean" 
        :value="is_compress_when_finish"
        @confirm="setConfigItem("is_compress_when_finish",$event.target.value)"
      id="isBuildFinshCompress"></ui-prop>
    </div>

  `,

  // element and variable binding
  $: {
    content: '#content',
    compressType: '#compressType',
    isBuildFinshCompress: '#isBuildFinshCompress',
    title: '#title',
    tinify_key: '#tinify_key',
    compress_btn: '#compress_btn',
    compress_progress: '#compress_progress',
  },


  // method executed when template and styles are successfully loaded and initialized
  ready() {
    Editor.url('assets/..')
    console.log('shadowRoot', this.shadowRoot)
    const myPanel = this;
    this._info.width = 800;
    const myVue = new window.Vue({
      el: this.shadowRoot,
      data: {
        is_single_log: false,
        title: 'fast compressor',
        log_list: [],
        is_compressing: false,
        compress_progress: 0,
        compress_judge: 'dont know yet',
        compress_judge_list: ["oops, try tiny bro，超过全国了0.99%的人", "不太行", "还能接受", "超过银河系了99.99%的人"],
        min_quality: 65,
        max_quality: 80,
        compress_type: 0,
        max_log_count: 1024,
        tinify_key: '',
        ignore_compressed_png: false,
        is_to_bottom_log: true,
        is_compress_when_finish: false
      },
      watch: {
        // compress_type: function (val, oldVal) {
        //   myVue.log('new: %s, old: %s', val, oldVal)
        //   this.setConfigItem('compress_type', val)
        // },
      },
      created() {
        Editor.log('mounted 1')
        this.$nextTick(function () {
          // 仅在整个视图都被渲染之后才会运行的代码
          // Editor.log('mounted 2', myPanel.$content.querySelector('#log_wrap'))
          // for (let i = 0; i < 30; i++) {
          //   setTimeout(()=>{
          //     this.log('hahaha' + i)
          //   },100*i)
          // }

          this.readConfigData(() => {
            let move_data = (local, config) => {
              for (let key in local) {
                this.getConfigItem(key, config[key])
                // if (local[key] != undefined && config[key] != undefined) {
                //   local[key] = config[key]
                //   this.log('my_', key, config[key])
                // }
              }
            }
            move_data(this.$data, config);
            // Editor.log('config.tinify_key', this)
            // this.$tinify_key.value = config.tinify_key;
            // this.$isBuildFinshCompress.value = config.isBuildFinshCompress;
          })
        })
      },
      methods: {
        readConfigData(cb) {
          Editor.Ipc.sendToMain('png_compressor:readConfig', (err, str) => {
            if (err) console.error(err);
            try {
              config = JSON.parse(str);
            } catch (e) {
            }
            this.log('读取配置', JSON.stringify(config))
            if (cb) cb(config);
          }, -1)
        },
        writeConfigData(cb) {
          this.log('writeConfigData', JSON.stringify(config))
          Editor.Ipc.sendToMain('png_compressor:writeConfig', JSON.stringify(config), (err) => {
            this.log('writeConfigData  完成', JSON.stringify(config))
            if (cb) cb(err);
          }, -1)
        },
        setConfigItem(key, val) {
          this.log('setConfigItem', key, val, config)
          if (key && config && this.$data[key] != undefined) {
            this.$data[key] = val;
            config[key] = val;
            this.writeConfigData()
            // this.log('setConfigItem2', key, config[key], this.$data[key])
          }
        },
        getConfigItem(key) {
          if (key && config[key] != undefined && this.$data[key] != undefined) {
            this.$data[key] = config[key];
            // this.log('getConfigItem', key, config[key])
          }
        },
        clearAllLog(event) {
          const log_wrap = myPanel.$content.querySelector('#log_wrap')
          while (log_wrap.children.length > 0) {
            log_wrap.removeChild(log_wrap.children[0])
          }
          // let list = [];
          // for (let i = 0; i < log_wrap.children.length; i++) {
          //   list.push(log_wrap.children[i]);
          // }
          // frameProcess(list, (item, idx) => {
          //   log_wrap.removeChild(item)
          // }, () => {
          // }, 1, 500)
        },
        log(...msg) {
          Editor.log(msg)
          return;
          const log_wrap = myPanel.$content.querySelector('#log_wrap')
          let date = new Date();
          let time = `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
          let log_el = document.createElement('div')
          // msg = msg.reduce((pre, cur, idx) => {
          //   if (cur != undefined) {
          //     if (typeof cur == 'object') {
          //       cur = JSON.stringify(cur);
          //     }
          //     pre = pre + " " + cur;
          //   }
          // }, "")
          msg = msg.join(' ');
          msg = time + " -:- " + msg;
          log_el.classList.add('log_item')
          // Editor.log('log', msg)
          log_el.innerText = msg;
          this.is_single_log = !this.is_single_log;
          if (this.is_single_log) {
            log_el.classList.add('single_log')
          } else {
            log_el.classList.add('double_log')
          }
          log_wrap.appendChild(log_el);
          this.log_list.push(log_el);
          if (this.log_list.length > this.max_log_count) {
            let out_item = this.log_list.shift()
            log_wrap.removeChild(out_item);
          }
          if (this.is_to_bottom_log) {
            log_wrap.scrollTop = log_wrap.scrollHeight
          }
        },
        compress(event) {
          this.compress_progress = 0;
          this.compress_judge = "dont know yet";
          event.target.disabled = true
          // this.log('compresser 获取压缩列表');
          let finish = (percent) => {
            // this.log('compresser 压缩完了', percent)
            // Editor.log('event.target', event.target)
            // delete event.target.disabled
            this.compress_progress = 100;
            myPanel.$compress_btn.disabled = null;
          }
          this.readConfigData((cfg) => {
            if (cfg) {
              Editor.log('config', cfg)
              let finish_cb = (err, percent, compress_rate) => {
                finish(percent)
                if (compress_rate > 80) {
                  this.compress_judge = "perfect";
                } else {
                  let idx = (compress_rate / 80) / (1 / this.compress_judge_list.length);
                  // this.log("idx", idx);
                  // this.log("compress_rate", compress_rate);
                  this.compress_judge = `${compress_rate}% | ${this.compress_judge_list[idx]}`;
                }
              }
              Editor.Ipc.sendToMain('png_compressor:compressWithConfig', cfg, finish_cb, -1)
            } else {
              Editor.error('no config')
              finish(100)
            }
          })

        },

      }

    });
    this.myVue = myVue;

  },

  // register your ipc messages here
  messages: {
    'hello'(event, data) {
      this.$title.innerText = 'Hello!' + data;
    },
    'set_compress_progress'(event, data, img, beforeSize, nowSize) {
      if (beforeSize != undefined && nowSize != undefined && this.myVue) {
        this.myVue.log(`${img}压缩了 ${(nowSize - beforeSize) / beforeSize * 100}%`)
      }
      this.$compress_progress.value = data;
    },
  }
});

// "i18n:MAIN_MENU.package.title/png_compressor/一键压缩所有png": {
//   "message": "png_compressor:startCompress"
// }


